package com.haixiaoke.saas.org.service.impl;

import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.constant.UserConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.org.domain.Dept;
import com.haixiaoke.saas.org.domain.User;
import com.haixiaoke.saas.org.mapper.UserMapper;
import com.haixiaoke.saas.org.service.IDeptService;
import com.haixiaoke.saas.org.service.IUserService;
import com.haixiaoke.saas.system.domain.LoginBody;
import com.haixiaoke.saas.system.framework.security.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户Service业务层处理
 * 
 * @author panda
 * @date 2025-06-03
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IDeptService deptService;

    /**
     * 查询用户
     * 
     * @param userId 用户主键
     * @return 用户
     */
    @Override
    public User selectUserByUserId(Long userId) {
        return userMapper.selectUserByUserId(userId);
    }

    /**
     * 查询用户列表
     * 
     * @param user 用户
     * @return 用户
     */
    @Override
    public List<User> selectUserList(User user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 新增用户
     * 
     * @param user 用户
     * @return 结果
     */
    @Override
    public AjaxResult insertUser(User user) {
        if (user.getDeptId() == null) {
            return AjaxResult.error("请选择部门");
        }
        List<Map<String, Object>> maps = userMapper.checkParams(user);
        if (CollectionUtil.isNotEmpty(maps)) {
            for (Map<String, Object> map : maps) {
                if (Integer.parseInt(map.get("num").toString()) > 0) {
                    String type = map.get("type").toString();
                    switch (type) {
                        case "1":
                            return AjaxResult.error("用户名称已存在，请重新输入");
                        case "2":
                            return AjaxResult.error("手机号码已存在，请重新输入");
                    }
                }
            }
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setCreateTime(DateUtils.getNowDate());
        int result = userMapper.insertUser(user);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改用户
     * 
     * @param user 用户
     * @return 结果
     */
    @Override
    public AjaxResult updateUser(User user) {
        if (user.getDeptId() == null) {
            return AjaxResult.error("请选择部门");
        }
        List<Map<String, Object>> maps = userMapper.checkParams(user);
        if (CollectionUtil.isNotEmpty(maps)) {
            for (Map<String, Object> map : maps) {
                if (Integer.parseInt(map.get("num").toString()) > 0) {
                    String type = map.get("type").toString();
                    switch (type) {
                        case "1":
                            return AjaxResult.error("用户名称已存在，请重新输入");
                        case "2":
                            return AjaxResult.error("手机号码已存在，请重新输入");
                    }
                }
            }
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateTime(DateUtils.getNowDate());
        int result = userMapper.updateUser(user);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 批量删除用户
     * 
     * @param userIds 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteUserByUserIds(Long[] userIds) {
        return userMapper.deleteUserByUserIds(userIds);
    }

    /**
     * 删除用户信息
     * 
     * @param userId 用户主键
     * @return 结果
     */
    @Override
    public int deleteUserByUserId(Long userId) {
        return userMapper.deleteUserByUserId(userId);
    }

    @Override
    public int editUser(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public AjaxResult checkUser(LoginBody loginBody) {
        if (StrUtil.isEmpty(loginBody.getUsername()) || StrUtil.isEmpty(loginBody.getPassword())
                || StrUtil.isEmpty(loginBody.getPermissionChar())) {
            return AjaxResult.error("组织架构数据异常");
        }
        User user = userMapper.selectUserByUserName(loginBody.getUsername());
        if (ObjectUtil.isEmpty(user)) {
            return AjaxResult.error("组织架构用户不存在");
        }
        if (StrUtil.equals(UserConstants.USER_DISABLE, user.getUserState())) {
            return AjaxResult.error("用户已被禁用，请联系管理员");
        }
        if (!SecurityUtils.matchesPassword(loginBody.getPassword(), user.getPassword())) {
            return AjaxResult.error("密码不正确");
        }
        Dept dept = deptService.selectDeptByPermissionChar(loginBody.getPermissionChar());
        if (ObjectUtil.isEmpty(dept)) {
            return AjaxResult.error("组织架构部门不存在");
        }
        if (StrUtil.equals(UserConstants.DEPT_DISABLE, dept.getStatus())) {
            return AjaxResult.error("部门已被禁用，请联系管理员");
        }
        return null;
    }

    @Override
    public User selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    @Override
    public User selectUserByPhone(String userPhone) {
        return userMapper.selectUserByPhone(userPhone);
    }
}
